// import 'package:flutter_app/helper.dart';
// import 'package:flutter_app/services/api.dart';
// import 'package:flutter_app/views/mall_app/main_app/logic.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/services/api.dart';

import '../../../router.dart';
import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class CommodityKeywordSearchLogic extends GetxController {
  final CommodityKeywordSearchState state = CommodityKeywordSearchState();
  // final MainAppLogic mainAppLogics = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());

  @override
  void onInit() {
    super.onInit();

    // state.searchFocusNode = FocusNode();

    print(' Get.arguments   = ${Get.arguments}');
    state.searchTextEditingController.text = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
    getHotSearchList();
    getAdvertising();
  }

  /// 获取热搜榜单
  void getHotSearchList() {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var shopId = SpUtil.getInt("storeShopNum");
      var isThird = SpUtil.getInt(Config.IS_CHANGE_SHOP) ?? 0;

      if (isThird == 1) {
        shopId = SpUtil.getInt("thirdStoreShopNum");
      }
      Map<String, dynamic> params = {
        // 'customer_type': 3,
        "title": state.searchTextEditingController.text,
        // "shop_id": SpUtil.getInt("storeShopNum"),
        // "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
        "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
        "shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
        "use_platform": 2,

        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "page_no": state.currentPage,
        "page_size": state.pageSize,
        "access_token": SpUtil.getString("token")
      };

      print(">>>>>>>>!@!!!!!$params");
      if (state.salesRankingSorting) {
        params["order_by"] = "sold_quantity desc";
      }
      if (state.priceSorting != null) {
        if (state.priceSorting) {
          params["order_by"] = "price desc";
        } else {
          params["order_by"] = "price asc";
        }
      }
      if (state.isNewest) {
        params["order_by"] = "onsale_time desc";
      }

      print("获取热搜榜单的参数：$params");

      Api.getSearchList(params).listen((event) {
        state.refreshController.loadComplete();
        state.refreshController.refreshCompleted();
        print("获取热搜榜单========：$event");
        // if (event["code"] == 0) {
        if (event["lists"] != null) {
          List list = event["lists"];
          if (state.currentPage == 1) {
            if (list != null) {
              state.commodityList = list;
            }
          } else {
            if (list != null) {
              state.commodityList.addAll(list);
            }
          }
          if (list != null && list.length > 0) {
            List goodLists = [];
            list.forEach((element) {
              goodLists.add('${element['default_item_num_id']}');
            });
            var params2 = {
              "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
              "super_ec_shop_num_id":
                  SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
              'item_num_id_list': goodLists,
            };
            Api.shopTag(params2).listen((event) {
              print(' 商品列表 角标信息  ======================  event = $event');
              if (event['code'] == 0) {
                // Map<String, dynamic> goodsMap = {
                //   'widgets_data_id': dataMap['widgets_data_id'],
                //   'listMap': event['tag_list'] ?? [],
                // };
                // state.angleInformationList.add(goodsMap);
                List angleList = event['tag_list'];
                if (state.currentPage == 1) {
                  state.angleInformationList = angleList;
                } else {
                  state.angleInformationList.addAll(angleList);
                }
              }
              update();
            });
          }
          if ((list == null || list.isEmpty || list.length < state.pageSize) &&
              state.commodityList.length > 0) {
            if (state.currentPage > 1) {
              state.refreshController.loadNoData();
            }
          }
          update();
        }
        // }
        if (state.commodityList.length == 0) {
          getRecommendCommodityList();
          // getAdvertising();
        }
      });
    });
  }

  /// 下拉刷新
  void refreshData() {
    state.currentPage = 1;
    getHotSearchList();
    state.refreshController.refreshCompleted();
  }

  /// 上拉加载更多
  void loadMoreData() {
    state.currentPage++;
    getHotSearchList();
    state.refreshController.loadComplete();
  }

  /// 综合排序点击事件
  void comprehensiveSortingClickEvent() {
    state.comprehensiveSorting = true;
    state.salesRankingSorting = false;
    state.priceSorting = null;
    state.isNewest = false;
    update();
    refreshData();
  }

  /// 销量排序点击事件
  void salesRankingSortingClickEvent() {
    state.comprehensiveSorting = false;
    state.salesRankingSorting = true;
    state.priceSorting = null;
    state.isNewest = false;
    update();
    refreshData();
  }

  /// 价格排序点击事件
  void priceSortingClickEvent() {
    state.comprehensiveSorting = false;
    state.salesRankingSorting = false;
    if (state.priceSorting == null) {
      state.priceSorting = true;
    } else {
      state.priceSorting = !state.priceSorting;
    }
    state.isNewest = false;
    update();
    refreshData();
  }

  /// 上新排序点击事件
  void isNewestSortingClickEvent() {
    state.comprehensiveSorting = false;
    state.salesRankingSorting = false;
    state.priceSorting = null;
    state.isNewest = true;
    update();
    refreshData();
  }

  /// 取消搜索
  void cancelSearch() {
    state.searchTextEditingController.clear();
    update();
    refreshData();
  }

  /// 获取推荐商品列表
  void getRecommendCommodityList() {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "use_platform": 2,
        "is_recommend": 1,
        "shop_id": SpUtil.getInt("storeShopNum"),
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "page_no": 1,
        "page_size": 10,
        "access_token": SpUtil.getString('token')
      };
      Api.recommendGoods(params).listen((event) {
        print("获取推荐商品列表:$event");
        if (event["code"] == 0) {
          List list = event["lists"];
          if (list != null) {
            state.recommendCommodityList = list;
            update();
          }
        }
      });
    });
  }

  /// 加入购物车
  void requestAddGoods(String ecShopNumId, String itemNumId, String styleNumId,
      String ecStyleNumId) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": 1.0,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": ecStyleNumId,
      'access_token': SpUtil.getString('token'),
    };
    Api.addShoppingCart(params).listen((event) {
      print(event);
      if (event['code'] == 0) {
        mainLogic.getCartNum();
        toast('添加成功');
      } else {
        toast(event['message']);
      }
    });
  }

  // 获取广告内容
  void getAdvertising() {
    print('获取广告列表');
    var params = {
      'adv_category': '1',
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      if (event["code"] == 0 && event["list"] != null) {
        state.advertising = event['list'];
        print('获取广告列表---${state.advertising}');
      } else {
        state.advertising = [];
      }
      update();
    });
  }

// 进入商品详情
  void enterGoodsDetail(style_num_id, ec_style_num_id, cat_id,
      default_item_num_id, shop_num_id, is_pre_sale) {
    String itemNumId = default_item_num_id.toString();
    String styleNumId = style_num_id.toString();
    String ecStyleNumId = ec_style_num_id.toString();
    Get.toNamed(RouteConfig.goodsDetail, arguments: {
      'itemNumId': itemNumId,
      'styleNumId': styleNumId,
      'shopId': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'].toString(),
      'ecStyleNumId': ecStyleNumId,
      'typeIndex': is_pre_sale,
    });
  }
}
